package com.axonactive.yolo.notification;

import java.util.List;

import com.axonactive.yolo.domain.SubscribedFlight;
import com.axonactive.yolo.domain.TaskUserId;
import com.axonactive.yolo.domain.User;
import com.axonactive.yolo.dto.Flight;

public class FlightNotifier {
	private final int SENDSMSFORCANCELFLIGHT=0;
	private final int SENDSMSFORCHANGEPRICEFLIGHT=1;
	private final int SENDSMSFORCHANGESCHEDULEFLIGHT=2;
	private final int SENDSMSFORTASK=3;

	private static FlightNotifier instance;
	private SMSService smsService;
	private Template smsTemplate;

	//private constructor, so i don't allow create an instance of this class explicitly
	private FlightNotifier() {
		smsService=new TwilioSMSService();
		smsTemplate=new SMSTemplate();
	}
	public static FlightNotifier getInstance() {
		if (instance == null) {
			instance = new FlightNotifier();
		}
		return instance;
	}

	public boolean sendSMSForCancelFlight(SubscribedFlight subscribedFlight, List<User> users)
	{
		return sendBroadcast(SENDSMSFORCANCELFLIGHT, subscribedFlight, users);
	}

	public boolean sendSMSForChangePriceFlight(SubscribedFlight subscribedFlight, List<User> users)
	{
		return sendBroadcast(SENDSMSFORCHANGEPRICEFLIGHT, subscribedFlight, users);
	}

	public boolean sendSMSForChangeScheduleFlight(SubscribedFlight subscribedFlight, List<User> users)
	{
		return sendBroadcast(SENDSMSFORCHANGESCHEDULEFLIGHT, subscribedFlight, users);
	}
	
	public boolean sendSMSForTask(List<Flight> flights, User user, TaskUserId takTaskUserId) {
		boolean res=true;
		String body = smsTemplate.getFlightFromTaskBody(flights, takTaskUserId);

		if (smsService.sendMessage(user.getPhone(), body)==false){
			res=false;
		}
		return res;
	}

	private boolean sendBroadcast(int type, SubscribedFlight subscribedFlight, List<User> users)
	{
		boolean res=true;
		for (User user : users) {
			if(!user.isSendViaSMS()){
				continue;
			}

			String body;
			if(type==SENDSMSFORCANCELFLIGHT) body=smsTemplate.getCanceledFlightBody(subscribedFlight);
			else if(type==SENDSMSFORCHANGEPRICEFLIGHT) body=smsTemplate.getChangePriceFlightBody(subscribedFlight, user.getCurrency());
			else body=smsTemplate.getChangeScheduleFlightBody(subscribedFlight);

			if (smsService.sendMessage(user.getPhone(), body)==false){
				res=false;
			}
		}
		return res;
	}
}
